package com.example.BOOK;

import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.BOOK.data.Book;
import com.example.BOOK.data.Databank;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BookListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */

public class BookListFragment extends Fragment {
    public static final int  adddate = 007;
    public static final int menuidupdate = 3;
    public static final int REQUEST_CODE = 444;
    public static final int request = 222;
    public static final int menuidedit = 4;
    public static final int requestedit =555;
    private List<Book> books;
    private BookListFragment.MyRecyclerViewAdapter recycleviewadapter;
    private Databank databank;

    List getListBooks() {
        return books;
    }

    ActivityResultLauncher<Intent> launcherUpdate = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== adddate){
                if(null==data)return;
                String name=data.getStringExtra("name");
                int position=data.getIntExtra("position",books.size());
                books.add(position,new Book(name, R.drawable.book_no_name));
                databank.savedata();
                recycleviewadapter.notifyItemInserted(position);

            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode==adddate) {
                if(null==data)return;
                String name = data.getStringExtra("name");
                double price = data.getDoubleExtra("price", 0);
                int position = data.getIntExtra("position",  books.size());
                books.get(position).setName(name);
                databank.savedata();
                recycleviewadapter.notifyItemChanged(position);
            }
        }

    });
    public BookListFragment() {
        // Required empty public constructor
    }


    public static BookListFragment newInstance() {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView=inflater.inflate(R.layout.fragment_book_list, container, false);
        initData();

        FloatingActionButton fabAdd=rootView.findViewById(R.id.floating_action_button_add);
        fabAdd.setOnClickListener(view -> {
            Intent intent=new Intent(this.getContext(), EditBookActivity.class);
            intent.putExtra("position",books.size());
            launcherUpdate.launch(intent);
        });
        RecyclerView mainRecycleView = rootView.findViewById(R.id.recycle_view_items);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        mainRecycleView.setLayoutManager(layoutManager);

        recycleviewadapter = new BookListFragment.MyRecyclerViewAdapter(books);
        mainRecycleView.setAdapter(recycleviewadapter);
        return rootView;
    }


    public void initData() {
        databank = new Databank( BookListFragment.this.getContext());
        books= databank.loadData();
    }

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter<BookListFragment.MyRecyclerViewAdapter.MyViewHolder> {
        private List<Book> books;

        public MyRecyclerViewAdapter(List<Book> books) {
            this.books = books;
        }

        @NonNull
        @Override
        public BookListFragment.MyRecyclerViewAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book_holder, parent, false);

            return new BookListFragment.MyRecyclerViewAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull BookListFragment.MyRecyclerViewAdapter.MyViewHolder Holder, int position) {
            Holder.getImageView().setImageResource(books.get(position).getCoverResourceId());
            Holder.getTextViewName().setText(books.get(position).getTitle());
        }

        @Override
        public int getItemCount() {
            return books.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
            public static final int menuiddelete =1;
            public static final int menuidadd = 2;
            private final ImageView imageView;
            private final TextView textViewName;

            public MyViewHolder(View view) {
                super(view);
                this.imageView = view.findViewById(R.id.image_view_book_cover);
                this.textViewName = view.findViewById(R.id.text_view_book_title);
                view.setOnCreateContextMenuListener(this);
            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                int position = getAdapterPosition();
                MenuItem delete = menu.add(ContextMenu.NONE, menuiddelete, menuiddelete, "Delete"+position  );
                MenuItem add=menu.add(ContextMenu.NONE,menuidadd,menuidadd,"Add"+position);
                MenuItem update=menu.add(ContextMenu.NONE,menuidupdate,menuidupdate,"Update"+position);
                MenuItem edit=menu.add(ContextMenu.NONE,menuidedit,menuidedit,"Edit"+position);
                delete.setOnMenuItemClickListener(this);
                add.setOnMenuItemClickListener(this);
                update.setOnMenuItemClickListener(this);
                edit.setOnMenuItemClickListener(this);
            }

            public boolean onMenuItemClick(MenuItem item) {
                final int position=getAdapterPosition();
                Intent intent;

                switch (item.getItemId())
                {

                    case menuiddelete:
                        AlertDialog.Builder alertDB = new AlertDialog.Builder( BookListFragment.this.getContext());
                        alertDB.setPositiveButton(BookListFragment.this.getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                            books.remove(position);
                            databank.savedata();
                            BookListFragment.MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                        });
                        alertDB.setNegativeButton(BookListFragment.this.getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        });
                        alertDB.setMessage(BookListFragment.this.getResources().getString(R.string.string_confirm_delete) +books.get(position).getTitle()+"？");
                        alertDB.setTitle(BookListFragment.this.getResources().getString(R.string.hint)).show();
                        break;

                    case menuidadd:
                        books.add(position,new Book(books.get(position).getTitle(),books.get(position).getCoverResourceId()));
                        databank.savedata();
                        BookListFragment.MyRecyclerViewAdapter.this.notifyItemInserted(position);
                        break;

                    case menuidupdate:
                        intent=new Intent( BookListFragment.this.getContext(), EditBookActivity.class);
                        intent.putExtra("position",position);
                        launcherUpdate.launch(intent);
                        break;
                    case menuidedit:
                        intent=new Intent( BookListFragment.this.getContext(),EditBookActivity.class);
                        intent.putExtra("position",position);
                        intent.putExtra("name",books.get(position).getTitle());
                        launcherEdit.launch(intent);

                }
                return false;
            }
        }
    }
}